## Kucik, Peritz, Puig (2022) "Legalization and Compliance"
## Replication of Precedent Descriptive Statistics
## TABLES 1 and 2

## Initial steps
rm(list=ls(all=T))
library(haven)

# Set your working directory here
setwd("/Users/lperitz/Dropbox/JK_LP/RulingExpansion/BJPS/bjps22_replication")

## Data -----------------------------------------

# read in data and subset
d<- read_dta("precedent_data.dta")


## Table 1 --------------------------------------  
# Number of applications
table(d$referencecategorygrouped)

# Percent of total applications
round(table(d$referencecategorygrouped)/nrow(d), 2)*100

# Percent of AB reports
pctABrep <- function(d,p.form){
  X <- length(unique(d$citingabreport[d$referencecategorygrouped==p.form]))
  Y <- length(unique(d$citingabreport))
  print(p.form)
  return(round(X/Y, 2)*100)
}

pctABrep(d, "Distinguishes")
pctABrep(d, "Extends")
pctABrep(d, "Follows")
pctABrep(d, "Narrows")

## Summary statistics in Section 3.1 ----------------------------

# AB ruling on DS 282
sort(unique(d$citedabreport[d$citingabreport==282]))
nrow(d[d$citingabreport==282,])
table(d$referencecategorygrouped[d$citingabreport==282])


## Table 2 ------------------------------------------------------

l <- unique(d$agreementscited[d$agreementscited!=""])

calcT2 <- function(d, a){
  n <- nrow(d[d$agreementscited==a,])
  ex <- nrow(d[d$agreementscited==a&d$referencecategorygrouped=="Extends",])
  s <- round(ex/n,3)
  return(cbind(n, ex, s))
}

T2 <- matrix(NA, nrow = length(l), ncol = 3)
rownames(T2) <- l
colnames(T2) <- c("Cites", "Extensions", "Share")

for(i in 1:length(l)){
  T2[i,]<-calcT2(d, l[i])
}

T2 <- T2[order(T2[,"Share"], decreasing=TRUE),]
T2[1:10,]


## END ------------------------